 /* Copyright (c) 2007 Pentaho Corporation.  All rights reserved. 
 * This software was developed by Pentaho Corporation and is provided under the terms 
 * of the GNU Lesser General Public License, Version 2.1. You may not use 
 * this file except in compliance with the license. If you need a copy of the license, 
 * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho 
 * Data Integration.  The Initial Developer is Pentaho Corporation.
 *
 * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" 
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to 
 * the license for the specific language governing your rights and limitations.*/

 
/*
 * Created on 18-mei-2003
 *
 */

package com.dc.trans.steps.message2row;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPreviewFactory;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.rowgenerator.RowGeneratorMeta;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;


/**
 * 
 * @author wujzb
 * @since 2012-09-04
 */
public class Message2RowDialog extends BaseStepDialog implements StepDialogInterface
{
	private static Class<?> PKG = Message2RowMeta.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

	private Label        wlFields;
	private TableView    wFields;
	private FormData     fdlFields, fdFields;

	private Message2RowMeta input;

	public Message2RowDialog(Shell parent, Object in, TransMeta transMeta, String sname)
	{
		super(parent, (BaseStepMeta)in, transMeta, sname);
		input=(Message2RowMeta)in;
	}

	public String open()
	{
		Shell parent = getParent();
		Display display = parent.getDisplay();

		shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
 		props.setLook(shell);
        setShellImage(shell, input);

		ModifyListener lsMod = new ModifyListener() 
		{
			public void modifyText(ModifyEvent e) 
			{
				input.setChanged();
			}
		};
		changed = input.hasChanged();

		FormLayout formLayout = new FormLayout ();
		formLayout.marginWidth  = Const.FORM_MARGIN;
		formLayout.marginHeight = Const.FORM_MARGIN;

		shell.setLayout(formLayout);
		shell.setText(BaseMessages.getString(PKG, "Message2RowDialog.DialogTitle"));
		
		int middle = props.getMiddlePct();
		int margin = Const.MARGIN;

		// Filename line
		wlStepname=new Label(shell, SWT.RIGHT);
		wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
 		props.setLook(wlStepname);
		fdlStepname=new FormData();
		fdlStepname.left = new FormAttachment(0, 0);
		fdlStepname.right= new FormAttachment(middle, -margin);
		fdlStepname.top  = new FormAttachment(0, margin);
		wlStepname.setLayoutData(fdlStepname);
		wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
		wStepname.setText(stepname);
 		props.setLook(wStepname);
		wStepname.addModifyListener(lsMod);
		fdStepname=new FormData();
		fdStepname.left = new FormAttachment(middle, 0);
		fdStepname.top  = new FormAttachment(0, margin);
		fdStepname.right= new FormAttachment(100, 0);
		wStepname.setLayoutData(fdStepname);

		wlFields=new Label(shell, SWT.NONE);
		wlFields.setText(BaseMessages.getString(PKG, "Message2RowDialog.Fields.Label"));
 		props.setLook(wlFields);
		fdlFields=new FormData();
		fdlFields.left = new FormAttachment(0, 0);
		fdlFields.top  = new FormAttachment(wStepname, margin);
		wlFields.setLayoutData(fdlFields);
		
		final int FieldsRows=input.getChangeFileds().length;
		
		ColumnInfo[] colinf=new ColumnInfo[] { 
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Name"),       ColumnInfo.COLUMN_TYPE_TEXT,   false),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Type"),       ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Format"),     ColumnInfo.COLUMN_TYPE_FORMAT, 2),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Length"),     ColumnInfo.COLUMN_TYPE_TEXT,   false),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Precision"),  ColumnInfo.COLUMN_TYPE_TEXT,   false),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Currency"),   ColumnInfo.COLUMN_TYPE_TEXT,   false),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Decimal"),    ColumnInfo.COLUMN_TYPE_TEXT,   false),
		 new ColumnInfo(BaseMessages.getString(PKG, "System.Column.Group"),      ColumnInfo.COLUMN_TYPE_TEXT,   false),
		};
		
		wFields=new TableView(transMeta, shell, 
						      SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, 
						      colinf, 
						      FieldsRows,  
						      lsMod,
							  props
						      );

		fdFields=new FormData();
		fdFields.left  = new FormAttachment(0, 0);
		fdFields.top   = new FormAttachment(wlFields, margin);
		fdFields.right = new FormAttachment(100, 0);
		fdFields.bottom= new FormAttachment(100, -50);
		wFields.setLayoutData(fdFields);

		wOK=new Button(shell, SWT.PUSH);
		wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
        wCancel=new Button(shell, SWT.PUSH);
		wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
		
        setButtonPositions(new Button[] { wOK, wCancel }, margin, null);
        
		// Add listeners
		lsOK       = new Listener() { public void handleEvent(Event e) { ok();     } };
		lsCancel   = new Listener() { public void handleEvent(Event e) { cancel(); } };
		
		wOK.addListener      (SWT.Selection, lsOK    );
		wCancel.addListener  (SWT.Selection, lsCancel);
		
		lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
		
		wStepname.addSelectionListener( lsDef );
		// Detect X or ALT-F4 or something that kills this window...
		shell.addShellListener(	new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );

		lsResize = new Listener() 
		{
			public void handleEvent(Event event) 
			{
				Point size = shell.getSize();
				wFields.setSize(size.x-10, size.y-50);
				wFields.table.setSize(size.x-10, size.y-50);
				wFields.redraw();
			}
		};
		shell.addListener(SWT.Resize, lsResize);
		
		// Set the shell size, based upon previous time...
		setSize();
		
		getData();
		input.setChanged(changed);
		
		shell.open();
		while (!shell.isDisposed())
		{
				if (!display.readAndDispatch()) display.sleep();
		}
		return stepname;
	}
	

	private void cancel()
	{
		stepname=null;
		input.setChanged(changed);
		dispose();
	}
	
	private void ok()
	{
		if (Const.isEmpty(wStepname.getText())) return;

		stepname = wStepname.getText(); // return value
        try
        {
            getInfo(input);                  // to put the content on the input structure for real if all is well.
            dispose();
        }
        catch(KettleException e)
        {
            new ErrorDialog(shell, BaseMessages.getString(PKG, "Message2RowDialog.Illegal.Dialog.Settings.Title"), BaseMessages.getString(PKG, "Message2Row.Illegal.Dialog.Settings.Message"), e);
        }
	}
	

	/**
	 * Copy information from the meta-data input to the dialog fields.
	 */ 
	public void getData()
	{
		if(isDebug()) logDebug("getting fields info...");
		
		for (int i=0;i<input.getChangeFileds().length;i++)
		{
				Message2RowField field = input.getChangeFileds()[i];
				TableItem item = wFields.table.getItem(i);
				item.setText(1, field.getName());
				if(isDebug()) logDebug("field #"+i+" --> fieldType[i]="+field.getTypeDesc());
				String type   = field.getTypeDesc();
				String format = field.getFormat();
				String length = field.getLength()<0?"":(""+field.getLength());
				String prec   = field.getPrecision()<0?"":(""+field.getPrecision());;
				String curr   = field.getCurrencySymbol();
				String group  = field.getGroupSymbol();
				String decim  = field.getDecimalSymbol();
				if (type  !=null) item.setText(2, type  ); else item.setText(2, "");
				if (format!=null) item.setText(3, format); else item.setText(3, "");
				if (length!=null) item.setText(4, length); else item.setText(4, "");
				if (prec  !=null) item.setText(5, prec  ); else item.setText(5, "");
				if (curr  !=null) item.setText(6, curr  ); else item.setText(6, "");
				if (decim !=null) item.setText(7, decim ); else item.setText(7, "");
				if (group !=null) item.setText(8, group ); else item.setText(8, "");
		}
        wFields.setRowNums();
        wFields.optWidth(true);
		
		wStepname.selectAll();
	}
	
	private void getInfo(Message2RowMeta meta) throws KettleException
    {
        int nrfields = wFields.nrNonEmpty();

        meta.allocate(nrfields);

        for (int i=0;i<nrfields;i++)
        {
        	Message2RowField field = new Message2RowField();;
            TableItem item = wFields.getNonEmpty(i);
            
            field.setName(item.getText(1));
            field.setType(ValueMeta.getType(item.getText(2)));
            field.setFormat(item.getText(3));
            String slength           = item.getText(4);
            String sprec             = item.getText(5);
            field.setCurrencySymbol(item.getText(6));
            field.setDecimalSymbol(item.getText(7));
            field.setGroupSymbol(item.getText(8));
            field.setLength(Const.toInt( slength, -1));
            field.setPrecision(Const.toInt( sprec  , -1));
            input.getChangeFileds()[i] = field;
        }
    }

    public String toString()
	{
		return this.getClass().getName();
	}

}